{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SMD (Server Machine Dataset)\n",
    "## 1. OC-SVM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyexpat.errors import XML_ERROR_UNEXPECTED_STATE\n",
    "import numpy as np\n",
    "from sklearn.linear_model import SGDOneClassSVM\n",
    "from sklearn.svm import OneClassSVM\n",
    "from sklearn.preprocessing import StandardScaler, MinMaxScaler\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "data_root = r\"E:\\迅雷下载\\异常检测\\SMD\"\n",
    "\n",
    "x_train = np.load(os.path.join(data_root, r\"SMD_train.npy\")) \n",
    "x_test = np.load(os.path.join(data_root, r\"SMD_test.npy\"))\n",
    "y_test = np.load(os.path.join(data_root, r\"SMD_test_label.npy\"))\n",
    "\n",
    "from sklearn.preprocessing import MinMaxScaler, StandardScaler\n",
    "scaler = StandardScaler()# StandardScaler() # MinMaxScaler()\n",
    "scaler.fit(x_train)\n",
    "x_train = scaler.transform(x_train)\n",
    "x_test = scaler.transform(x_test)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0001 err_train: 0.0\n",
      "0.001 err_train: 0.0\n",
      "0.01 err_train: 0.0\n",
      "1e-05 err_train: 0.0\n",
      "1e-06 err_train: 0.0\n",
      "0.1 err_train: 0.05159054495662792\n"
     ]
    }
   ],
   "source": [
    "debug = True\n",
    "if debug:\n",
    "    for nu in (1e-4, 1e-3, 1e-2, 1e-5, 1e-6, 0.1):\n",
    "        clf = SGDOneClassSVM(nu=nu, max_iter=500)\n",
    "        # clf = OneClassSVM(nu=nu, max_iter=500, kernel='poly', degree=2)\n",
    "\n",
    "        clf.fit(x_train)\n",
    "        preds_train = clf.predict(x_train)\n",
    "        err_train = sum(preds_train==-1)/len(preds_train)\n",
    "        print(nu, \"err_train:\", err_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "err_train: 0.00023574085445472577\n"
     ]
    }
   ],
   "source": [
    "nu = 0.04\n",
    "clf = SGDOneClassSVM(nu=nu, max_iter=2000, verbose=0)\n",
    "# clf = OneClassSVM(nu=nu, max_iter=1000, kernel='poly', degree=2)\n",
    "\n",
    "clf.fit(x_train)\n",
    "preds_train = clf.predict(x_train)\n",
    "err_train = sum(preds_train==-1)/len(preds_train)\n",
    "print(\"err_train:\", err_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Classification report for classifier \n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "         0.0     0.9584    0.9992    0.9784    678976\n",
      "         1.0     0.0036    0.0001    0.0001     29444\n",
      "\n",
      "    accuracy                         0.9577    708420\n",
      "   macro avg     0.4810    0.4996    0.4893    708420\n",
      "weighted avg     0.9187    0.9577    0.9377    708420\n",
      "\n",
      "\n",
      "Confusion matrix:\n",
      "[[678429    547]\n",
      " [ 29442      2]]\n"
     ]
    }
   ],
   "source": [
    "preds = clf.predict(x_test)\n",
    "preds[preds==1] = 0\n",
    "preds[preds==-1] = 1\n",
    "\n",
    "from sklearn import metrics\n",
    "print(\"Classification report for classifier \\n %s\\n\"\n",
    "      % ( metrics.classification_report(y_test, preds, digits=4)))\n",
    "print(\"Confusion matrix:\\n%s\" % metrics.confusion_matrix(y_test, preds))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6388938727343492"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "scores = clf.score_samples(x_test)\n",
    "metrics.roc_auc_score(y_test, scores)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py310",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
